package com.ldy.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;

public class Silk2Mp3Util {
	
	private static final Logger logger = LoggerFactory.getLogger(Silk2Mp3Util.class);
	private static String filePath = "/usr/local/src/wechat/silk-v3-decoder";
	static String SLK = ".slk";
	static String MP3 = ".mp3";

	public static String get(String silkBase64) {
		String id = UUID.randomUUID().toString();
		logger.info("Silk2Mp3: id: {}", id);
		// 写文件
		String silkPath = filePath + "/" + id + SLK;
		String mp3Path = filePath + "/" + id + MP3;
		try {

			byte[] decode = Base64.getDecoder().decode(silkBase64);
			
			FileUtil.writeBytes(decode, silkPath);
			
			// 指定要执行的Shell命令或脚本
			String command = "cd "+filePath+" && sh converter.sh " + id + SLK + " mp3";
			logger.info("Silk2Mp3: command: {}", command);
			// 创建ProcessBuilder对象并设置命令
			ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", command);

			// 将输出流与错误流合并
			processBuilder.redirectErrorStream(true);

			// 启动进程
			Process process = processBuilder.start();

			// 获取进程的输入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

			// 读取进程输出
			String line;
			while ((line = reader.readLine()) != null) {
				logger.info("Silk2Mp3: result: {}", line);
			}

			// 等待进程执行完毕
			int exitCode = process.waitFor();
			logger.info("Silk2Mp3: result code: {}", exitCode);
			if (exitCode == 0) {
				// 获取文件
				byte[] readBytes = FileUtil.readBytes(mp3Path);
				return Base64.getEncoder().encodeToString(readBytes);
			}

		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		} finally {
			try {
				FileUtil.del(silkPath);
				FileUtil.del(mp3Path);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	 public static void main(String[] args) {
	        try {
	            // 要执行的创建文件的Shell命令
	            String command = "cd /Users/lindeyi/workspace/MyProject/liuyan/silk2mp3/silk-v3-decoder && ffmpeg -version";

	            // 创建ProcessBuilder对象并设置命令
	            ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", command);
	        	// 将输出流与错误流合并
				processBuilder.redirectErrorStream(true);
	            // 启动进程
	            Process process = processBuilder.start();
	        

				// 获取进程的输入流
				BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

				// 读取进程输出
				String line;
				while ((line = reader.readLine()) != null) {
					System.out.println(line);
				}
	            // 等待进程执行完毕
	            int exitCode = process.waitFor();
	            
	            System.out.println("Process exited with code: " + exitCode);
	            

	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
}
